package co.za.itweb.brainstormlite;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.util.ByteArrayBuffer;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CioActivity extends Activity{
	
	 private GestureDetector mGestureDetector;
	    
	  private static float sideIndexX;
	  private static float sideIndexY;
	    
	  private int sideIndexHeight;
	    
	  private int indexListSize;
	  ContactList CL; 
	  ArrayList<ContactList> m_orders;
	  private OrderAdapter m_adapter;
	  private ProgressDialog m_ProgressDialog = null;
	  static Vector<ContactFeed> CList = new Vector<ContactFeed>(0);
	  RefreshTask rt;
	  private ArrayList<Object[]> indexList = null;
	  ListView lv1;
	  static String[] ar;
	  static boolean loaded=false;
	 
	
	@SuppressLint("ParserError")
	@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.contact);
	        LinearLayout layout = (LinearLayout) findViewById(R.id.cell4);
	        int colors[] =  {Color.parseColor("#FF1f292f"),Color.parseColor("#FF1f292f")};
			GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,colors);
			layout.setBackgroundDrawable(grad);
			
			TextView titletext=(TextView) findViewById(R.id.title);
		     titletext.setText("CIO Directory");
		    if(loaded==false){
		     rt = new RefreshTask(this);
				if (rt.getStatus() == AsyncTask.Status.PENDING) {
					// My AsyncTask has not started yet
					rt.execute();
				}
		    }else{
		    	afterAll();
		    }
				
				 ImageButton info=(ImageButton) findViewById(R.id.cell4).findViewById(R.id.info);
				 ImageButton back=(ImageButton) findViewById(R.id.cell4).findViewById(R.id.back);
			    // ImageButton category=(ImageButton) findViewById(R.id.cell4).findViewById(R.id.find);
			     
			     back.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent intent1 = new Intent(CioActivity.this,MenuActivity.class);
							intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent1);
							finish();
						}
					});
			     
			     
			     info.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							
							Intent intent = new Intent(getApplicationContext(), DialogActivity.class);
							startActivity(intent);
							
				
						}
					});
			     /*
			     category.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							
							Intent intent = new Intent(getApplicationContext(), CitiesActivity.class);
							startActivity(intent);
							
				
						}
					});
					*/
	 }
	
	public void afterAll(){
		
		 m_orders = new ArrayList<ContactList>();
	        for(int s=0;s<CList.get(0)._itemlist.size();s++){
	        	
	        	m_orders.add(CList.get(0)._itemlist.get(s));
	        }
	        
	        
	        ar=new String[CList.get(0)._itemlist.size()];
	        for(int y=0;y<CList.get(0)._itemlist.size();y++){
	        	ar[y]=CList.get(0)._itemlist.get(y).getContactName();
	        
	        }
	        
	       Arrays.sort(ar);
	      
            lv1 = (ListView) findViewById(R.id.ListView01);
	        this.m_adapter = new OrderAdapter(this,ar);
	        lv1.setAdapter(this.m_adapter);
	        lv1.setTextFilterEnabled(true);
	          
	           m_adapter.notifyDataSetChanged();
	        
	       // lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ar));
	        mGestureDetector = new GestureDetector(this, new SideIndexGestureListener());
	        
	        lv1.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					
					
					Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
					intent.putExtra("id", position);
					intent.putExtra("id2", 5000);
					
					startActivity(intent);
				}
			});
	        
	       
	      
	}
	 
	 @Override
	 public boolean onTouchEvent(MotionEvent event)
	 {
		 if(lv1.isShown()){
			
			
			 if (mGestureDetector.onTouchEvent(event)){
				 return true;
			 } else{
				 return false;
			 }
		 }
		 return false;
	 }
	 
	 
	 private ArrayList<Object[]> createIndex(String[] strArr)
	    {
	        ArrayList<Object[]> tmpIndexList = new ArrayList<Object[]>();
	        Object[] tmpIndexItem = null;

	        int tmpPos = 0;
	        String tmpLetter = "";
	        String currentLetter = null;
	        String strItem = null;

	        for (int j = 0; j < strArr.length; j++)
	        {
	            strItem = strArr[j];
	            currentLetter = strItem.substring(0, 1);
	           

	            // every time new letters comes
	            // save it to index list
	            if (!currentLetter.equals(tmpLetter))
	            {
	                tmpIndexItem = new Object[3];
	                tmpIndexItem[0] = tmpLetter;
	                tmpIndexItem[1] = tmpPos - 1;
	                tmpIndexItem[2] = j - 1;

	                tmpLetter = currentLetter;
	                tmpPos = j + 1;

	                tmpIndexList.add(tmpIndexItem);
	                
	            }
	        }

	        // save also last letter
	        tmpIndexItem = new Object[3];
	        tmpIndexItem[0] = tmpLetter;
	        tmpIndexItem[1] = tmpPos - 1;
	        tmpIndexItem[2] = strArr.length - 1;
	        tmpIndexList.add(tmpIndexItem);

	        // and remove first temporary empty entry
	        if (tmpIndexList != null && tmpIndexList.size() > 0)
	        {
	            tmpIndexList.remove(0);
	        }
	        
	        for(int g=0;g<tmpIndexList.size();g++){
	        
	        }
	        return tmpIndexList;
	    }

	    
	 @Override
	    public void onWindowFocusChanged(boolean hasFocus)
	    {
	        super.onWindowFocusChanged(hasFocus);
	        if(lv1.isClickable()){

	        final ListView listView = (ListView) findViewById(R.id.ListView01);
	        LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
	        sideIndexHeight = sideIndex.getHeight();
	        sideIndex.removeAllViews();

	        // TextView for every visible item
	        TextView tmpTV = null;

	        // we'll create the index list
	        
	       
	        
	      
	        indexList = createIndex(ar);
	       
	        // number of items in the index List
	        indexListSize = indexList.size();

	        // maximal number of item, which could be displayed
	        int indexMaxSize = (int) Math.floor(sideIndex.getHeight() / 20);
	        int tmpIndexListSize = indexListSize;
	        // handling that case when indexListSize > indexMaxSize
	        while (tmpIndexListSize > indexMaxSize)
	        {
	            tmpIndexListSize = tmpIndexListSize / 2;
	        }

	        // computing delta (only a part of items will be displayed to save a
	        // place)
	        double delta = indexListSize / tmpIndexListSize;

	        String tmpLetter = null;
	        Object[] tmpIndexItem = null;

	        // show every m-th letter
	        for (double i = 1; i <= indexListSize; i = i + delta)
	        {
	            tmpIndexItem = indexList.get((int) i - 1);
	            tmpLetter = tmpIndexItem[0].toString();
	            tmpTV = new TextView(this);
	            tmpTV.setText(tmpLetter);
	            tmpTV.setGravity(Gravity.CENTER);
	            tmpTV.setTextSize(20);
	            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1);
	            tmpTV.setLayoutParams(params);
	            sideIndex.addView(tmpTV);
	        }
	       
	        // and set a touch listener for it
	        sideIndex.setOnTouchListener(new OnTouchListener()
	        {
	            
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// now you know coordinates of touch
	                sideIndexX = event.getX();
	                sideIndexY = event.getY();

	                // and can display a proper item it country list
	                displayListItem();
					return false;
				}
	        });
	        
	        }
	    }

	    class SideIndexGestureListener extends
	            GestureDetector.SimpleOnGestureListener
	    {
	        @Override
	        public boolean onScroll(MotionEvent e1, MotionEvent e2,
	                float distanceX, float distanceY)
	        {
	            // we know already coordinates of first touch
	            // we know as well a scroll distance
	            sideIndexX = sideIndexX - distanceX;
	            sideIndexY = sideIndexY - distanceY;

	            // when the user scrolls within our side index
	            // we can show for every position in it a proper
	            // item in the country list
	            if (sideIndexX >= 0 && sideIndexY >= 0)
	            {
	                displayListItem();
	            }

	            return super.onScroll(e1, e2, distanceX, distanceY);
	        }
	        
	        
	    }

	    public void displayListItem()
	    {
	        // compute number of pixels for every side index item
	        double pixelPerIndexItem = (double) sideIndexHeight / indexListSize;

	        // compute the item index for given event position belongs to
	        int itemPosition = (int) (sideIndexY / pixelPerIndexItem);

	        // compute minimal position for the item in the list
	        int minPosition = (int) (itemPosition * pixelPerIndexItem);

	        // get the item (we can do it since we know item index)
	        Object[] indexItem = indexList.get(itemPosition);

	        // and compute the proper item in the country list
	        int indexMin = Integer.parseInt(indexItem[1].toString());
	        int indexMax = Integer.parseInt(indexItem[2].toString());
	        int indexDelta = Math.max(1, indexMax - indexMin);

	        double pixelPerSubitem = pixelPerIndexItem / indexDelta;
	        int subitemPosition = (int) (indexMin + (sideIndexY - minPosition) / pixelPerSubitem);

	        ListView listView = (ListView) findViewById(R.id.ListView01);
	        listView.setSelection(subitemPosition);
	    }
	    
	    private class OrderAdapter extends BaseAdapter {

	        private String[] items;
	        public  ImageLoader imageLoader; 
	        public OrderAdapter(Context context, String[] items) {
	               
	                this.items = items;
	                imageLoader=new ImageLoader(context);
	        }
	        @Override
	        public View getView(int position, View convertView, ViewGroup parent) {
	                View v = convertView;
	                if (v == null) {
	                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                    v = vi.inflate(R.layout.contact_row, null);
	                }
	               
	               
	                	TextView tt = (TextView) v.findViewById(R.id.toptext);
	                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
	                        ImageView iv=(ImageView) v.findViewById(R.id.icon);
	                      
	                        if (tt != null) {
	                              tt.setText(items[position]); 
	                        }
	                        if (iv != null) {
	                        	for(int t=0;t<CList.get(0)._itemlist.size();t++){
	                        		if(items[position].equals(CList.get(0)._itemlist.get(t).getContactName())){
	                   	                  int dot = CList.get(0)._itemlist.get(t).getContactIcon().lastIndexOf(".");
	                        			  String imageUrl = CList.get(0)._itemlist.get(t).getContactIcon().substring(dot - 1)+"_m.jpg";
	                        		    
	                        			
	                        				imageLoader.DisplayImage(CList.get(0)._itemlist.get(t).getContactIcon(), iv);
	                        			
	                        			
	                        			
	       	                        	 bt.setText("Company: "+CList.get(0)._itemlist.get(t).getCompany()+"\n"+ "Category: "+CList.get(0)._itemlist.get(t).getCategory()); 
	       	                        
	                        		}
	                        	}
	                        	 
	                        }
	                        
	                        
	                
	                return v;
	        }
	        
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return items.length;
			}
			@Override
			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return items[position];
			}
			@Override
			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return position;
			}
	}
	    
	    
	    
	    private class RefreshTask extends AsyncTask<Void, Integer, Void> {
	    	
			ContactFeed feed;
			ProgressDialog dialog;
			public RefreshTask(CioActivity activity) {
				dialog = new ProgressDialog(activity);
			}

			protected void onPreExecute() {
				dialog = ProgressDialog.show(CioActivity.this, "",
						"Fetching directory...");
				dialog.setCancelable(true);
				dialog.setMax(100);
				dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
			          public void onCancel(DialogInterface dialog) {
			        	  CList.clear();
			  			CioActivity.this.finish();
			          }
			    });
			}

			@Override
			protected Void doInBackground(Void... params) {
				
					if(DownloadFromUrl("http://itweb.mobi/brainstorm_android/feed/ios-v1.php?source=iphone&tag=cio","cio.xml")){
					
					feed = parseLocalXml(Environment.getExternalStorageDirectory() + "/co.za.itweb.brainstormlite/cio.xml");
					
					
					
					if (feed != null) {
						System.out.println("ADDED FEED");
						CList.add(feed);

						
						
						if (isCancelled()) {

						CList.clear();

							
							finish();

							return null;
						}

					}
					}

				return null;
			}

			

			@Override
			protected void onPostExecute(Void result) {
				if (dialog.isShowing()) {
					dialog.dismiss();
					loaded=true;
				}
				afterAll();
				
			}
		}
		
	    
	    
	    public boolean DownloadFromUrl(String DownloadUrl, String fileName) {

			   try {
			           File root = android.os.Environment.getExternalStorageDirectory();               

			           File dir = new File (Environment.getExternalStorageDirectory() + "/co.za.itweb.brainstormlite/");
			           if(dir.exists()==false) {
			                dir.mkdirs();
			           }

			           URL url = new URL(DownloadUrl); //you can write here any link
			           File file = new File(dir, fileName);

			           long startTime = System.currentTimeMillis();
			           Log.d("DownloadManager", "download begining");
			           Log.d("DownloadManager", "download url:" + url);
			           Log.d("DownloadManager", "downloaded file name:" + fileName);

			         
			           URLConnection ucon = url.openConnection();

			           InputStream is = ucon.getInputStream();
			           BufferedInputStream bis = new BufferedInputStream(is);

			          
			           ByteArrayBuffer baf = new ByteArrayBuffer(100*1024);
			           int current = 0;
			           while ((current = bis.read()) != -1) {
			              baf.append((byte) current);
			           }


			       
			           FileOutputStream fos = new FileOutputStream(file);
			           fos.write(baf.toByteArray());
			           fos.flush();
			           fos.close();
			           
			           Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
	                   return true;
			   } catch (IOException e) {
			       Log.d("DownloadManager", "Error: " + e);
			       return false;
			   }

			}
	    
	    public ContactFeed parseLocalXml(String filename){
			try {

				//URL url = new URL(urlToRssFeed);

				SAXParserFactory factory = SAXParserFactory.newInstance();
				factory.setNamespaceAware(true);

				SAXParser parser = factory.newSAXParser();

				XMLReader xmlreader = parser.getXMLReader();

				ContactHandler theRssHandler = new ContactHandler();

				xmlreader.setContentHandler(theRssHandler);

				InputSource is = new InputSource(new FileInputStream(filename));
				
				xmlreader.parse(is);

				System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"
						+ theRssHandler.getFeed());
				return theRssHandler.getFeed();
			} catch (Exception ee) {
				System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
						+ ee.toString());
				return null;
			}
		}
	    
	    

}













